package com.swt.testdemo.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * shiro-session监听
 *
 * @author BleethNie
 * @version 1.0
 * @date 2020-01-09 09:48
 */
@Slf4j
public class ShiroSessionListener implements SessionListener {


    private static ConcurrentHashMap<Serializable, Session> sessionConcurrentHashMap = new ConcurrentHashMap<>();

    /**
     * 回话创建触发
     */
    @Override
    public void onStart(Session session) {
        if (session != null) {
            sessionConcurrentHashMap.put(session.getId(), session);
        }
    }

    /**
     * 退出会话时触发
     */
    @Override
    public void onStop(Session session) {
        if (session != null) {
            sessionConcurrentHashMap.remove(session.getId());
        }
    }

    /**
     * 会话过期时触发
     */
    @Override
    public void onExpiration(Session session) {
        if (session != null) {
            sessionConcurrentHashMap.remove(session.getId());
        }
    }

    public static Session getSession(String sessionId) {
        return sessionConcurrentHashMap.get(sessionId);
    }

}